from typing import List

from entity.processor import Processor
from entity.task import Task


class ScheduleAnalysis:
    def __init__(self, mean: float, variance: float, timeout_cnt: int):
        self.mean = mean
        self.variance = variance
        self.timeout_cnt = timeout_cnt


def calc_execute_time(task: Task, p: Processor) -> float:
    task_len = task.length()
    exec_time = task_len / p.compute_ability
    return exec_time


def analyze_schedule_result(tasks: List[Task], s_map: dict, p_map: dict) -> ScheduleAnalysis:
    m_map = dict()
    for pid in p_map:
        m_map[pid] = 0

    timeout_cnt = 0
    for t in tasks:
        tid = t.id
        pid = s_map[tid]
        p = p_map[pid]
        exec_time = calc_execute_time(t, p)
        m_map[pid] += exec_time
        if m_map[pid] > t.deadline:
            timeout_cnt += 1

    tot = 0
    for pid in m_map:
        tot += m_map[pid]

    mean = tot / len(m_map)

    variance = 0
    for pid in m_map:
        variance += (m_map[pid] - mean) ** 2

    return ScheduleAnalysis(mean, variance, timeout_cnt)
